<?php

namespace app\manage\controller;

use think\Controller;
use think\Cache;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Api extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function getToken()
    {
        $token = $this->request->token();
        return json(['token' => $token]);
    }
    public function  val()
    {
        //验证token
        $res = $this->validate(['__token__' => $this->request->get('token')], ['__token__'  =>  'require|token']);
        if($res !== true) {
            print_r($res);
            
        } else {
            print_r('ok');
        }
    }
    
    public function audio()
    {
        
        /*$audio_token = cache('audio_token');//Cache::get('audio_token');
        if(!$audio_token) {
            $auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=lUnBesbRSXd3FEaljNTj7PWX&client_secret=PgGqbNRi8PEr4x7GaeBYc51y586r7GNj";
            $res = get_url($auth_url);
            $response = json_decode($res, true);
            if (!isset($response['access_token'])){
                return json(['msg' => 'ERROR TO OBTAIN TOKEN'], 400);
            }
            if (!isset($response['scope'])){
                return json(['msg' => 'ERROR TO OBTAIN scopes'], 400);
            }
            if (!in_array('audio_tts_post',explode(" ", $response['scope']))){
                return json(['msg' => 'DO NOT have tts permission'], 400);
            }
            cache('audio_token', $response['access_token'], 86400);
            $audio_token = $response['access_token'];//Cache::set('audio_token',$response['access_token'], 86400);
        }
        $params = array(
            'tex' => urlencode($this->request->get('content')), // 为避免+等特殊字符没有编码，此处需要2次urlencode。
            'per' => 0,  #发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
            'spd' => 4,  #语速，取值0-15，默认为5中语速
            'pit' => 5,  #音调，取值0-15，默认为5中语调
            'vol' => 7,  #音量，取值0-9，默认为5中音量
            'aue' => 'mp3',
            'cuid' => '123456PHP',
            'tok' => $audio_token,
            'lan' => 'zh', //固定参数
            'ctp' => 1, // 固定参数
        );
        $paramsStr =  http_build_query($params);
        $url = 'http://tsn.baidu.com/text2audio';
        $urltest = $url . '?' . $paramsStr;
        return \think\Response::create(file_get_contents($urltest))->header('Content-Type', 'audio/mp3');*/
        $audio_token = cache('audio_token');
        if(!$audio_token) {
            AlibabaCloud::accessKeyClient("LTAIueT5eYviSfqu", "oYYZTqA8Ejxipa2grbYlFRsM0plL22")->regionId("cn-shanghai")->asGlobalClient();
            try {
                $response = AlibabaCloud::NlsCloudMeta()->v20180518()->createToken()->request();
                if($response->Token) {
                    $audio_token = $response->Token->Id;
                    cache('audio_token', $response->Token->Id, 43200);
                } else {
                    return "token 获取失败\n";
                }
            } catch (ClientException $exception) {
                // 获取错误消息
                return $exception->getErrorMessage();
            } catch (ServerException $exception) {
                // 获取错误消息
                return $exception->getErrorMessage();
            }
        }
        $params = array(
            "appkey" => 'RjRlozfsldai1CF5',
            "token" => $audio_token,
            "text" => $this->request->get('content'),
            "format" => 'mp3',
            "sample_rate" => 16000,
            // voice 发音人，可选，默认是xiaoyun
            "voice" => "siqi",
            // volume 音量，范围是0~100，可选，默认50
             "volume" => 55,
            // speech_rate 语速，范围是-500~500，可选，默认是0
            "speech_rate" => -10,
            // pitch_rate 语调，范围是-500~500，可选，默认是0
            // "pitch_rate" => 0
        );
        $paramsStr =  http_build_query($params);
        $url = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts";
        $urltest = $url . '?' . $paramsStr;
        return \think\Response::create(file_get_contents($urltest))->header('Content-Type', 'audio/mp3');
    }
    
    public function getUser()
    {
        $list = model('user')->where('mobile', 'like', '%'.$this->request->get('params').'%')->field('id, mobile')->limit(10)->select();
        return [
            'code'    => 0,
            'msg'     =>  "",
            "count"   => 10,
            "data"    =>  $list
        ];
    }
}
